<template>
  <div>
    <el-form ref="ruleFormRef"
    :model="skuInfo"
    :rules="skuRules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize">

    <el-form-item label="SPU名称"  >
      <span>{{props.currentSpuInfo.spuName}}</span>
    </el-form-item>

    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="SKU名称"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number v-model="skuInfo.price" :min="1" style="width:100%" :max="100" controls-position="right" />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number v-model="skuInfo.weight" :min="1" style="width:100%" :max="100" controls-position="right" />
    </el-form-item>

      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input type="textarea" v-model="skuInfo.skuDesc" :rows="3" placeholder="SKU描述"></el-input>
      </el-form-item>

    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="10">
        <el-col v-for="(attr,index) in attrList" :key="attr.id" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <el-form-item :label="attr.attrName">
            <el-select placeholder="请选择" v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>


    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(saleAttr,index) in spuSaleAttrList" :key="saleAttr.id" :md="8" :sm="8" :xs="24" :lg="12">
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @click="clearSaleAttrRules">
              <el-option v-for="(saleAttrValue,index) in saleAttr.spuSaleAttrValueList" :value="`${saleAttrValue.id}:${saleAttrValue.saleAttrName}:${saleAttrValue.spuId}:${saleAttrValue.saleAttrValueName}`" :label="saleAttrValue.saleAttrValueName" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>


    <el-form-item label="图片列表" prop="skuImageList">
       <!-- 给表格一个数据源 -->
       <!-- 可选择表格会给一个选择函数 selection-change  -->
      <el-table border :data="spuImageList"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60">
        </el-table-column>

        <el-table-column label="图片" >
          <template v-slot="{row,$index}">
            <el-image :src="row.imgUrl" :alt="row.imgName" style="width:100px;height:100px"/>
          </template>
        </el-table-column>

        <el-table-column label="名称" prop="imgName">

        </el-table-column>
       
        <el-table-column label="操作" >
          <template v-slot="{row}">
            <el-button type="primary" v-if="row.isDefault==='0'" @click="setDefault(row)">设为默认项</el-button>
            <el-button type="success" v-else disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="emits('changeScene',1)">取消</el-button>
    </el-form-item>

    </el-form>
  </div>
</template>

<script lang="ts">
export default {
name:'SkuForm'
}
</script>

<script lang="ts" setup>
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqSaveSkuInfo} from '@/api/product/sku'
import { reqGetAttrListDataByCategory3Id } from '@/api/product/attr'
import { onMounted,ref,reactive } from 'vue'

import { useCategorySelectorInfoStore } from '@/stores/categorySelector'

//引入表单校验规则
import {ElMessage} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()

const categoryStore = useCategorySelectorInfoStore()
const props = defineProps(['currentSpuInfo'])
const emits = defineEmits(['getSpuInfo', 'changeScene'])

//准备变量,接收响应过来的数据

const num = ref(0)
const weight = ref(0)
// 图片列表
const spuImageList = ref([])
// spu基础属性列表
const spuSaleAttrList = ref([])
// 平台属性列表
const attrList = ref([])

//收集添加sku的参数

const skuInfo = reactive({
  // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],

  spuId: -1,

  category3Id :-1
})


// 1. 组件挂载完毕就要发送请求
onMounted(async ()=>{
  const id = props.currentSpuInfo.id
  const [resSpuImgageList,resSpuSaleAttrList,resAttrList] =await Promise.allSettled([reqGetSpuImageList(id),reqGetSpuSaleAttrList(id),reqGetAttrListDataByCategory3Id({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number
  })])
  console.log(resSpuImgageList,resSpuSaleAttrList,resAttrList)
  // 赋值
  if(resSpuImgageList.status==='fulfilled'){
    spuImageList.value = resSpuImgageList.value.map(item => {
      return {
        ...item,
        isDefault:'0'
      }
    })
  }
  if(resSpuSaleAttrList.status==='fulfilled'){
    spuSaleAttrList.value = resSpuSaleAttrList.value
  }
  if(resAttrList.status==='fulfilled'){
    attrList.value = resAttrList.value
  }

  console.log('skuForm',spuImageList,attrList,spuSaleAttrList);
  
})

//  单击设为默认项按钮 设置为默认图片
const setDefault = (row)=>{
  //排他思想 先将所有选项的设置为0
  spuImageList.value.forEach(item=>{
    item.isDefault = '0'
  })
  // 自己的设置为1
  row.isDefault = '1'

  //保存一下默认图片的地址

  skuInfo.skuDefaultImg = row.imgUrl
}

//定义自定义校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  console.log('自定义校验',rule,value,callback);
  if (value.length<3) {
    return callback('请至少选择3张图片')
  }
  //判断选中的图片是否有默认项
  const flag = value.some(item => item.isDefault === '1');
  if (!flag) return callback(new Error('选择的图片中不包含默认项,请添加默认项'));

  callback(); // 最终放行
}



// 书写校验规则

const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入SKU名称', trigger: 'blur' },
    { min: 2, max: 20, message: 'Sku名称在2---20之间', trigger: 'blur' },
  ],
  price: [
    {
      required: true,
      message: '请输入Sku价格',
      trigger: 'change',
    },
  ],
  weight: [
    {
      required: true,
      message: '请输入SKU重量',
      trigger: 'change',
    },
  ],
  skuDesc: [
    {
      required: true,
      message: '请输入Sku描述',
      trigger: 'blur',
    },
  ],

  skuImageList: [
    {
      type: 'array',
      required: true,
       trigger: 'change',
       //自定义校验,属性值为自定义校验的名字
       validator:skuImageListValidate
    },
  ],

  skuAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请至少选择三项平台属性',
      trigger: 'change'
    }],
  skuSaleAttrValueList: [
    {
      type: 'array',
      required: true,
      message: '请至少选择一项销售属性',
      trigger: 'change'
    }]

})

// 清空平台属性的校验规则
const clearAttrRules = () => {

  console.log('清除校验规则',ruleFormRef.value)
  
  ruleFormRef.value?.clearValidate(['skuAttrValueList'])
}

// 清空销售属性的校验规则
const clearSaleAttrRules = () => {
  ruleFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item=>{
        const [attrId,attrName,valueId,valueName] = item.split(':')
        return {
          attrId,attrName,valueId,valueName
        }
      })
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item=>{
        const [saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName] = item.split(':')
        return {
          saleAttrId,saleAttrName,saleAttrValueId,saleAttrValueName
        }
      })
      skuInfo.spuId = props.currentSpuInfo.spuId
      skuInfo.category3Id = categoryStore.category3Id as number
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success('添加Sku成功...')
      // 跳转到列表页
      emits('changeScene',1)
    } else {
      console.log('error submit!', fields)
    }
  })
}

//获取所选图片的地址
const handleSelectionChange = (val)=>{
  console.log('选择的图片',val)
  skuInfo.skuImageList = val
}

</script>

<style lang="scss" scoped>

</style>